﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Common.Session;
using Core.Message;
using Core.ExceptionHandling;
using Core.NTier.UserInterface;
using Telerik.Web.UI;
using System.Collections.ObjectModel;
using Core.Security.Business;
using Core.Cache;
using Core.Security.CoreMembership;
using Core.Controls.Message;
using Core.Message.Entities;


public partial class Controls_LeftMenu : Core.NTier.UserInterface.BaseUserControl
{
    #region Constant defined
    private const char _PATH_SEPERATOR = '/';
    private const string _PATH_ROOT = "~";
    protected const string A_TAG = "<a href='{0}'>{1}</a>";
    protected const string SEP = " » ";
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        this.LoadFavorites();
        this.LoadMenuBar();
        if (!IsPostBack)
        {
            this.LoadCurrentLink();
            cboUsername.SelectedValue = SessionManager.UserDelegate;
        }
        
    }
    /// <summary>
    /// Sự kiện thay đổi tên đăng nhập
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cboUsername_SelectedIndexChanged(object sender,
        Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
    {
        Session["UserDelegate"] = cboUsername.SelectedValue;
        Response.Redirect("~/Default.aspx");
    }
    protected void LoadFavorites() {
        try
        {
            /*
             * Tam thoi bo cach lam cua HungDV
             *
            Collection<RadPanelItem> leftMenuItems = new Collection<RadPanelItem>();
            SessionCacheManager cacher = new SessionCacheManager();
            CacheKey key = new CacheKey("Controls_LeftMenu", "RadLeftMenu", "LoadFavorites");
            if (cacher.Contains(key))
            {
                Collection<RadPanelItem> favs = (Collection<RadPanelItem>)cacher.GetData(key);
                RadLeftMenu.Items.AddRange(favs.ToArray());
            }
            else
            {
                ModulesBL favModule = new FavoritesBL().GetFavoritesModule();
                string moduleName = favModule.NameEN;
                if (SessionManager.IsVietnammese) moduleName = favModule.NameVN;
                Telerik.Web.UI.RadPanelItem root = new Telerik.Web.UI.RadPanelItem(moduleName);
                root.Value = favModule.ModuleId.ToString();

                Collection<FunctionsBL> functions = new FavoritesBL().GetFavoritesForUser(SessionManager.Username);
                foreach (FunctionsBL func in functions)
                {
                    string functionName = func.NameEN;
                    if (SessionManager.IsVietnammese) functionName = func.NameVN;
                    Telerik.Web.UI.RadPanelItem item = new Telerik.Web.UI.RadPanelItem(functionName);
                    item.Value = func.FunctionId.ToString();
                    item.NavigateUrl = "~" + func.VirtualPath;
                    root.Items.Add(item);
                }
                leftMenuItems.Add(root);
                RadLeftMenu.Items.Add(root);
                cacher.Add(key, leftMenuItems);
            }
             */
            if (SessionManager.UserDelegate.Equals("")) //Nếu không tồn tại việc chuyển qua quyền của delegate thì load menu sở thích, ngược lại thì không load.
            {
                Collection<FunctionsBL> functions = new Collection<FunctionsBL>();
                Collection<RadPanelItem> leftMenuItems = new Collection<RadPanelItem>();

                ModulesBL favModule = new FavoritesBL().GetFavoritesModule();
                string moduleName = favModule.NameEN;
                if (SessionManager.IsVietnammese) moduleName = favModule.NameVN;
                Telerik.Web.UI.RadPanelItem root = new Telerik.Web.UI.RadPanelItem(moduleName);
                root.Value = favModule.ModuleId.ToString();

                if (DataCache.GetCache("LoadFavorites_" + SessionManager.Username) == null) //Kiểm tra coi có cache này chưa
                {
                    functions = new FavoritesBL().GetFavoritesForUser(SessionManager.Username);
                    DataCache.SetCache("LoadFavorites_" + SessionManager.Username, functions);

                }

                functions = (Collection<FunctionsBL>)DataCache.GetCache("LoadFavorites_" + SessionManager.Username);

                RadLeftMenuFavor.Items.Clear();
                foreach (FunctionsBL func in functions)
                {
                    string functionName = func.NameEN;
                    if (SessionManager.IsVietnammese) functionName = func.NameVN;
                    Telerik.Web.UI.RadPanelItem item = new Telerik.Web.UI.RadPanelItem(functionName);
                    item.Value = func.FunctionId.ToString();
                    item.NavigateUrl = "~" + func.VirtualPath;
                    root.Items.Add(item);
                }
                leftMenuItems.Add(root);
                RadLeftMenuFavor.Items.Add(root);
            }
            
        }
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
    }

    /// <summary>
    /// Xây dựng leftmenu từ Db
    /// Lưu cache kết quả theo Session. Menu sẽ được Build lại khi người dùng logout và đăng nhập lại
    /// Cây menu chỉ có 2 cấp: Module & Function
    /// </summary>
    protected void LoadMenuBar()
    {
        Collection<RadPanelItem> leftMenuItems = new Collection<RadPanelItem>();        
        try
        {
            long currModuleId = RequestInfo.ModuleId;
            long currFunctionId = RequestInfo.MasterFunctionId;
            if (currModuleId <= 0) return;
            if (SessionManager.UserDelegate.Equals("")) //Nếu không tồn tại việc chuyển qua quyền của delegate thì load menu sở thích
            {
                #region Thuc hien viec load menu left
                if (DataCache.GetCache("LoadMenuBar_" + currModuleId.ToString() + SessionManager.Username) == null) //Kiểm tra coi có cache này chưa
                {
                    #region Bo code cu cua HungDV
                    ////create Module Panel
                    //ModulesBL m = new ModulesBL().FindById(currModuleId);

                    //string moduleName = m.NameEN;
                    //if (SessionManager.IsVietnammese) moduleName = m.NameVN;
                    //Telerik.Web.UI.RadPanelItem root = new Telerik.Web.UI.RadPanelItem(moduleName);
                    //root.Value = m.ModuleId.ToString();

                    //root.Expanded = true;
                    //root.Selected = true;

                    ////get list of function in the module
                    //Collection<FunctionsBL> functions = new FunctionsBL().FindByModule(m.ModuleId, SessionManager.Username);
                    //foreach (FunctionsBL func in functions)
                    //{
                    //    string functionName = func.NameEN;
                    //    if (SessionManager.IsVietnammese) functionName = func.NameVN;
                    //    Telerik.Web.UI.RadPanelItem item = new Telerik.Web.UI.RadPanelItem(functionName);
                    //    item.Value = func.FunctionId.ToString();
                    //    if (string.IsNullOrEmpty(func.VirtualPath) == false) item.NavigateUrl = "~" + func.VirtualPath;

                    //    //set StyleSelected
                    //    if (func.FunctionId == currFunctionId)
                    //    {
                    //        item.Selected = true;
                    //        item.Expanded = true;
                    //    }
                    //    else item.Expanded = false;
                    //    root.Items.Add(item);
                    //}
                    #endregion
                    string moduleName = "";

                    //get list of Sub menu
                    //create Module Panel
                    Collection<FunctionsBL> funcSub = new FunctionsBL().FindSubMenuByModule(currModuleId);
                    foreach (FunctionsBL sub in funcSub)
                    {
                        moduleName = sub.NameEN;
                        if (SessionManager.IsVietnammese) moduleName = sub.NameVN;
                        Telerik.Web.UI.RadPanelItem root = new Telerik.Web.UI.RadPanelItem(moduleName);
                        root.Value = sub.ModuleId.ToString();

                        root.Expanded = false;
                        root.Selected = false;


                        //get list of sub function in ParentID
                        Collection<FunctionsBL> Subfunctions = new FunctionsBL().FindByParent(sub.FunctionId, SessionManager.Username);
                        foreach (FunctionsBL func in Subfunctions)
                        {
                            string functionName = func.NameEN;
                            if (SessionManager.IsVietnammese) functionName = func.NameVN;
                            Telerik.Web.UI.RadPanelItem item = new Telerik.Web.UI.RadPanelItem(functionName);
                            item.Value = func.FunctionId.ToString();
                            if (string.IsNullOrEmpty(func.VirtualPath) == false) item.NavigateUrl = "~" + func.VirtualPath;

                            root.Items.Add(item);
                        }
                        leftMenuItems.Add(root);
                        RadLeftMenu.Items.Add(root);
                    }

                    //leftMenuItems.Add(root);
                    //RadLeftMenu.Items.Add(root);
                    
                    DataCache.SetCache("LoadMenuBar_" + currModuleId.ToString() + SessionManager.Username, leftMenuItems);

                }

                leftMenuItems = (Collection<RadPanelItem>)DataCache.GetCache("LoadMenuBar_" + currModuleId.ToString() + SessionManager.Username);

                RadLeftMenu.Items.Clear();
                foreach (RadPanelItem item in leftMenuItems)
                {
                    item.Expanded = false;
                    if (item.Value == currModuleId.ToString())
                    {

                        item.Selected = true;
                        item.Expanded = true;
                    }
                    RadPanelItem cItem = item.Items.FindItemByValue(currFunctionId.ToString());
                    if (cItem != null)
                    {

                        cItem.Selected = true;
                        cItem.Expanded = true;
                    }
                    RadLeftMenu.Items.Add(item);
                }
                #endregion

                
            }
            else //Load menu thuoc quyen delegate
            {
                #region Thuc hien viec load menu thuoc quyen cua delegate
                if (DataCache.GetCache("LoadMenuBarDelegate_" + currModuleId.ToString() + SessionManager.UserDelegate) == null) //Kiểm tra coi có cache này chưa
                {
                    string moduleName = "";

                    //get list of Sub menu
                    //create Module Panel
                    Collection<FunctionsBL> funcSub = new FunctionsBL().FindSubMenuByModule(currModuleId);
                    foreach (FunctionsBL sub in funcSub)
                    {
                        moduleName = sub.NameEN;
                        if (SessionManager.IsVietnammese) moduleName = sub.NameVN;
                        Telerik.Web.UI.RadPanelItem root = new Telerik.Web.UI.RadPanelItem(moduleName);
                        root.Value = sub.ModuleId.ToString();

                        root.Expanded = false;
                        root.Selected = false;


                        //get list of sub function in ParentID
                        Collection<FunctionsBL> Subfunctions = new FunctionsBL().FindByParentDelegate(sub.FunctionId, SessionManager.UserDelegate, SessionManager.Username);
                        foreach (FunctionsBL func in Subfunctions)
                        {
                            string functionName = func.NameEN;
                            if (SessionManager.IsVietnammese) functionName = func.NameVN;
                            Telerik.Web.UI.RadPanelItem item = new Telerik.Web.UI.RadPanelItem(functionName);
                            item.Value = func.FunctionId.ToString();
                            if (string.IsNullOrEmpty(func.VirtualPath) == false) item.NavigateUrl = "~" + func.VirtualPath;

                            root.Items.Add(item);
                        }
                        leftMenuItems.Add(root);
                        RadLeftMenu.Items.Add(root);
                    }


                    DataCache.SetCache("LoadMenuBarDelegate_" + currModuleId.ToString() + SessionManager.UserDelegate, leftMenuItems);

                }

                leftMenuItems = (Collection<RadPanelItem>)DataCache.GetCache("LoadMenuBarDelegate_" + currModuleId.ToString() + SessionManager.UserDelegate);

                RadLeftMenu.Items.Clear();
                foreach (RadPanelItem item in leftMenuItems)
                {
                    item.Expanded = false;
                    if (item.Value == currModuleId.ToString())
                    {

                        item.Selected = true;
                        item.Expanded = true;
                    }
                    RadPanelItem cItem = item.Items.FindItemByValue(currFunctionId.ToString());
                    if (cItem != null)
                    {

                        cItem.Selected = true;
                        cItem.Expanded = true;
                    }
                    RadLeftMenu.Items.Add(item);
                }
                #endregion
            }
        }
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }

    }

    /// <summary>
    /// Đường dẫn tới trang hiện hành
    /// </summary>
    public string FunctionPath
    {
        get
        {
            return Server.HtmlDecode(this.txtCurrentLink.Text);
        }
    }

    private void LoadCurrentLink()
    {
        this.txtCurrentLink.Text = string.Empty;
        try
        {
            string strLink = string.Empty;
            long lFuntionId = RequestInfo.FunctionId;
            long lMasterId = RequestInfo.MasterFunctionId;
            if (lMasterId == lFuntionId)
            {
                //Current Link
                FunctionsBL funcBO = new FunctionsBL().FindById(lFuntionId);
                if (funcBO != null && funcBO.DTO != null)
                {
                    string strFName = (SessionManager.IsEnglish) ? funcBO.NameEN : funcBO.NameVN;
                    strLink = SEP + strFName;
                }
            }
            else
            {
                //Master link >> Curent link
                FunctionsBL funcBO = new FunctionsBL().FindById(lFuntionId);
                FunctionsBL masterBO = new FunctionsBL().FindById(lMasterId);
                if (funcBO != null && funcBO.DTO != null && masterBO != null && masterBO.DTO != null)
                {
                    string strFName = (SessionManager.IsEnglish) ? funcBO.NameEN : funcBO.NameVN;
                    string strMName = (SessionManager.IsEnglish) ? masterBO.NameEN : masterBO.NameVN;
                    strLink = SEP + string.Format(A_TAG, ".." + masterBO.VirtualPath, strMName);
                    strLink += SEP + strFName;
                }
            }
            this.txtCurrentLink.Text= Server.HtmlEncode(strLink);
        }
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
        
    }
}